/**
 * 描述：表单维护页面初始化
 * 作者：zhaohaibo
 * 日期：3/22/2019
 * 版本：0.0.1
 **/

(function(E, KIT, RES) {
    var __URL_ROOT = RES.URL_FORM_DESIGNER_ROOT;

    //region ---------------------------- 请求地址 ----------------------------
    var __URL_FORM_FIND = __URL_ROOT + "/findForm",
        __URL_FORM_ADD = __URL_ROOT + "/addForm",
        __URL_FORM_UPDATE = __URL_ROOT + "/updateForm",
        __URL_FORM_REMOVE = __URL_ROOT + "/removeForm",
        __URL_FORM_TOGGLE_DISABLED = __URL_ROOT + "/toggleDisabledForm",
        __URL_FORM_CASCADE_FIELD = __URL_ROOT + "/findCascadeFileds";
    var __URL_FORM_FIELDS_FIND = __URL_ROOT + "/findFormFields",
        __URL_FORM_FIELD_ADD = __URL_ROOT + "/addFormField",
        __URL_FORM_FIELD_UPDATE = __URL_ROOT + "/updateFormField",
        __URL_FORM_FIELD_TOGGLE_DISABLED = __URL_ROOT + "/toggleDisabledField";

    var __URL_FORM_ROLES_FIND = __URL_ROOT + "/getDataRoleList",
        __URL_FORM_ROLES_ADD = __URL_ROOT + "/addRoles",
        __URL_FORM_ROLES_UPDATE = __URL_ROOT + "/updateRoles",
        __URL_FORM_ROLES_REMOVE = __URL_ROOT + "/removeRoles";

    //endregion ------------------------- 请求地址 ----------------------------

    var __AUDIT_SEQS = [{
        text: "1", value: "1"
    }, {
        text: "2", value: "2"
    }, {
        text: "3", value: "3"
    }, {
        text: "4", value: "4"
    }, {
        text: "5", value: "5"
    }, {
        text: "6", value: "6"
    }];

    var __SEPARATOR_TYPES = [{
        text: "_ (下划线)", value: "_"
    }, {
        text: "- (分隔符)", value: "-"
    }, {
        text: ". (句号)", value: "."
    }, {
        text: "/ (斜线)", value: "/"
    }, {
        text: "无分隔符", value: ""
    }];

    //region ---------------------------- 编辑控件类型 ----------------------------
    var __EDITOR_TYPES = [{
        text: "文本输入框", value: "textbox"
    },{
        text: "多行文本输入框", value: "textarea"
    }, {
        text: "数字输入框", value: "numberbox"
    }, {
        text: "带小数点的数字输入框", value: "digitbox"
    }, {
        text: "单项选择器", value: "picker"
    }, {
        text: "模糊单项选择器", value: "pickeredit"
    }, {
        text: "日期时间选择器", value: "datetimepicker"
    }, {
        text: "日期选择器", value: "datepicker"
    }, {
        text: "时间选择器", value: "timepicker"
    }, {
        text: "开关选择器", value: "switchbutton"
    }, {
        text: "富文本编辑器", value: "wangeditor"
    }, {
        text: "文件上传", value: "webuploader"
    },
        {
            text: "多项选择器", value: "pickermultiple"
        } /*,

         {
         text: "模糊多项选择器", value: "pickermultipleedit"
       },{
         text: "多选按钮", value: "checkboxlist"
       },{
         text: "单选按钮", value: "radiolist"
       },*/];
    //endregion ------------------------- 编辑控件类型 ----------------------------

    //region ---------------------------- 表单字段 Grid Fields ----------------------------
    var __GRID_FIELDS = [{
        title: "名称", name: "title", width: 200, size: 6, frozen: true,
        editor: {
            validator: {
                rules: {required: true, maxlength: 100}
            }
        }
    }, {
        title: "映射值字段名", name: "name", size: 6, frozen: true, width: 180,
        editor: {
            type: "picker",
            tip: "请选择...",
            autoReload: true,
            dataSource: {
                textField: "name",
                valueField: "name",
                url: __URL_ROOT + "/getAttribList",
                data: function() {
                    return {
                        formid: rapid("#grd").grid().tag("form_id")
                    }
                }
            },
            validator: {
                rules: {required: true}
            }
        }
    }, {
        title: "显示文本的字段名", name: "grid_show_name", width: 80,
        editor: {
            validator: {
                rules: {
                    maxlength: 20
                }
            }
        }
    }, {
        title: "控件类型", name: "type", width: 150,
        formatter: function(value, text, css) {
            var __len = __EDITOR_TYPES.length,
                __type = value;

            for(var __i = 0; __i < __len; __i++) {
                if(__EDITOR_TYPES[__i].value == __type) {
                    return __EDITOR_TYPES[__i].text;
                }
            }

            css.color = 7;
            css.italic = true;
            return "";

        },
        editor: {
            type: "picker",
            dataSource: __EDITOR_TYPES,
            validator: {
                rules: {required: true}
            },
            onchange: function(e) {
                var __value = this.val();
                _setDataSourceUi(__value, e);
                //_setUploaderFileSizeUi(__value, e);
            }
        }
    }, {
        title: "控件ID", name: "controller_id", width: 80,
        editor: {
            validator: {
                rules: {
                    maxlength: 20
                }
            }
        }
    }, {
        title: "是否在“表单”中占据一行", name: "col_span", align: "center", width: 80,
        formatter: function(value, text, css) {
            css.color = value == 12 ? 1 : null;
            return value == 12 ? "是" : "否";
        },
        editor: {
            name: "col_span", type: "checkbox", mode: "switch", checked: false,
            text: ["是", "否"],
            value: [12, 0]
        }
    }, {
        title: "是否在“表格”中隐藏", name: "grid_field_visible", align: "center", width: 80,
        formatter: function(value, text, css) {
            var __text = "";
            if(value == 1) {
                css.color = 1;
                __text = "是";
            } else {
                __text = "否";
            }
            return __text;
        },
        editor: {
            name: "grid_field_visible", type: "checkbox", mode: "switch", checked: false,
            text: ["是", "否"],
            value: [1, 0]
        }
    }, {
        title: "“表格列”宽度", name: "gird_field_width", width: 80,
        editor: {
            validator: {
                rules: {
                    integer: true
                }
            }
        }
    }, {
        title: "位置", name: "sort", width: 50,
        formatter: function(value, text, css) {
            return rapid.isEmpty(value) || value === 0 ? "" : value;
        },
        editor: {
            extraLabel: "数字大的靠前，可使用小数",
            validator: {
                rules: {
                    numeric: true
                }
            }
        }
    } ,{
        title: "是否级联", name: "is_cascade", align: "center", width: 80,
        formatter: function (value, text, css) {
            var __text = "";
            if (value == 1) {
                css.color = 6;
                __text = "必填项";
            }

            return __text;

        },
        editor: {
            name: "is_cascade", type: "checkbox", mode: "switch", checked: false,
            text: ["是", "否"], value: [1, 0],disabled: true,
            onchange: function (e) {
                var __value = this.val();

                if (__value == "1") {
                    e.ui("cascade_field").disabled(false);
                } else {
                    e.ui("cascade_field").val(null).disabled(true);
                }
            }
        }
    }, {
        title: "级联下级字段", name: "cascade_field", width: 150, editor: {
            name: "cascade_field",
            type: "picker",
            tip: "请选择...",
            textField: "cascade_field",
            valueField: "cascade_field",
            multiple: false,
            disabled: true,
            autoReload: true,
            dataSource: {
                textField: "cascade_field",
                valueField: "cascade_field",
                url: __URL_FORM_CASCADE_FIELD,
                data: function () {
                    return {
                        formid: rapid("#grd").grid().tag("form_id")
                    }
                }
            }
            // ,
            // autocomplete: {
            //   paramName: "search_name",
            //   dataSource: {
            //     textField: "ftitle",
            //     valueField: "ffield",
            //     url: __URL_FORM_CASCADE_FIELD,
            //     data: function () {
            //       return {
            //         formid: rapid("#grd").grid().tag("form_id")
            //       }
            //     }
            //   }
            // }
        }
    }, {
        title: "是否必填", name: "required", align: "center", width: 80,
        formatter: function(value, text, css) {
            var __text = "";
            if(value == 1) {
                css.color = 6;
                __text = "必填项";
            }

            return __text;

        },
        editor: {
            name: "required", type: "checkbox", mode: "switch", checked: true,
            text: ["是", "否"], value: [1, 0]
        }
    }, {
        title: "默认值", name: "default_value", width: 80,
        editor: {
            validator: {
                rules: {
                    maxlength: 50
                }
            }
        }
    }, {
        title: "字段最大长度", name: "string_max_length", width: 80,
        editor: {
            validator: {
                rules: {
                    integer: true
                }
            }
        }
    }, {
        title: "数字最小值", name: "number_min_value", width: 80,
        editor: {
            disabled: true,
            validator: {
                rules: {
                    required: true
                }
            }
        }
    }, {
        title: "数字最大值", name: "number_max_value", width: 80,
        editor: {
            disabled: true,
            validator: {
                rules: {
                    required: true
                }
            }
        }
    }, {
        title: "是否为查询条件", name: "is_search", align: "center", width: 80,
        formatter: function(value, text, css) {
            var __text = "";
            if(value == 1) {
                css.color = 1;
                __text = "是";
            } else {
                __text = "否";
            }
            return __text;
        },
        editor: {
            name: "is_search", type: "checkbox", mode: "switch", checked: false,
            text: ["是", "否"], value: [1, 0]
        }
    }, {
        title: "是否汇总项", name: "is_sum", align: "center", width: 80,
        formatter: function(value, text, css) {
            var __text = "";
            if(value == 1) {
                css.color = 1;
                __text = "是";
            } else {
                __text = "否";
            }
            return __text;
        },
        editor: {
            name: "is_sum", type: "checkbox", mode: "switch", checked: false,
            text: ["是", "否"], value: [1, 0]
        }
    }, {
        title: "是否为分类汇总字段", name: "is_typesum", align: "center", width: 80,
        formatter: function(value, text, css) {
            var __text = "";
            if(value == 1) {
                css.color = 1;
                __text = "是";
            } else {
                __text = "否";
            }
            return __text;
        },
        editor: {
            name: "is_typesum", type: "checkbox", mode: "switch", checked: false,
            text: ["是", "否"], value: [1, 0]
        }
    }, {
        title: "数据字典", name: "code_name", width: 200,
        editor: {
            name: "code_resource",
            disabled: true,
            type: "picker",
            tip: "请选择...",
            textField: "code_name",
            valueField: "code_resource",
            dataSource: {
                url: RES.URL_ROOT + "/code/getCodeTopInfo"
            },
            onchange: function(e) {
                if(rapid.isEmpty(this.value())) {
                    e.ui("code_leaf").val(null).disabled(true);
                } else {
                    if(rapid.isEmpty(e.ui("code_leaf").val())) {
                        e.ui("code_leaf").val(2);
                    }
                    e.ui("code_leaf").disabled(false);
                }
            }
        }
    }, {
        title: "叶节点", name: "code_leaf", width: 80,
        editor: {
            disabled: true,
            validator: {
                rules: {
                    integer: true,
                    min: 2,
                    max: 10
                }
            }
        }
    }, {
        title: "自定义数据连接", name: "custom_data_url", width: 80,
        editor: {
            disabled: true,
            validator: {
                rules: {
                    maxlength: 100
                }
            }
        }
    }, {
        title: "自定义数据参数", name: "custom_data_option", width: 80,
        editor: {
            disabled: true,
            validator: {
                rules: {
                    maxlength: 100
                }
            }
        }
    }, {
        title: "数据是否唯一", name: "data_only", align: "center", width: 80,
        formatter: function(value, text, css) {
            var __text = "";
            if(value == 1) {
                css.color = 1;
                __text = "是";
            } else {
                __text = "否";
            }
            return __text;
        },
        editor: {
            name: "data_only", type: "checkbox", mode: "switch", checked: false,
            text: ["是", "否"],
            value: [1, 0]
        }
    }, {
        title: "是否可导出", name: "is_export", align: "center", width: 80,
        formatter: function(value, text, css) {
            var __text = "";
            if(value == 1) {
                css.color = 1;
                __text = "是";
            } else {
                __text = "否";
            }
            return __text;
        },
        editor: {
            name: "is_export", type: "checkbox", mode: "switch", checked: true,
            text: ["是", "否"],
            value: [1, 0]
        }
    },{
        title: "是否可编辑", name: "is_editor", align: "center", width: 80,
        formatter: function(value, text, css) {
            var __text = "";
            if(value == 1) {
                css.color = 1;
                __text = "是";
            } else {
                __text = "否";
            }
            return __text;
        },
        editor: {
            name: "is_editor", type: "checkbox", mode: "switch", checked: true,
            text: ["是", "否"],
            value: [1, 0]
        }
    }, {
        title: "备注", name: "note", size: 12, width: 150, editor: true
    }];
    //endregion ------------------------- Grid 字段 ----------------------------

    var _setDataSourceUi = function(uiType, e, __pickertext) {

            if(uiType === "picker" || uiType === "checkboxlist" ||
                uiType === "radiolist" || uiType === "pickermultiple" ||
                uiType === "pickeredit" || uiType === "pickermultipleedit") {

                if(uiType === "picker"){

                    e.ui("is_cascade").disabled(false);
                    if(e.ui("is_cascade").val() == "1"){
                        e.ui("cascade_field").disabled(false);
                    }
                }

                e.ui("code_resource").disabled(false);

                e.ui("code_leaf").disabled(false);

                e.ui("custom_data_url").disabled(false);

                e.ui("custom_data_option").disabled(false);

                e.ui("number_max_value").val(null).disabled(true);

                e.ui("number_min_value").val(null).disabled(true);

            } else if(uiType === "numberbox") {

                e.ui("number_max_value").disabled(false)
                    .validator({
                        rules: {
                            numeric: false,
                            integer: true,
                            required: true
                        }
                    });

                e.ui("number_min_value").disabled(false)
                    .validator({
                        rules: {
                            numeric: false,
                            integer: true,
                            required: true
                        }
                    });

                e.ui("code_resource").val(null).disabled(true);

                e.ui("code_leaf").val(null).disabled(true);

                e.ui("custom_data_url").val(null).disabled(true);

                e.ui("custom_data_option").val(null).disabled(true);

            } else if(uiType === "digitbox") {

                e.ui("number_max_value").disabled(false)
                    .validator({
                        rules: {
                            integer: false,
                            numeric: true,
                            required: true
                        }
                    });

                e.ui("number_min_value").disabled(false)
                    .validator({
                        rules: {
                            integer: false,
                            numeric: true,
                            required: true
                        }
                    });

                e.ui("code_resource").val(null).disabled(true);

                e.ui("code_leaf").val(null).disabled(true);

                e.ui("custom_data_url").val(null).disabled(true);

                e.ui("custom_data_option").val(null).disabled(true);

            } else {

                e.ui("number_max_value").val(null).disabled(true);

                e.ui("number_min_value").val(null).disabled(true);

                e.ui("code_resource").val(null).disabled(true);

                e.ui("code_leaf").val(null).disabled(true);

                e.ui("custom_data_url").val(null).disabled(true);

                e.ui("custom_data_option").val(null).disabled(true);

            }
        },

        _setUploaderFileSizeUi = function(uiType, e) {
            e.ui("file_size").disabled(uiType !== "imageuploader");
            e.ui("file_max_size").disabled(uiType !== "imageuploader");
        },

        _toggleDisabled = function(url, id, itemName, itemTypeName, buttonText, callback) {
            rapid.confirm(
                "确定要" + buttonText + "“" + itemName + "”" + itemTypeName + "吗？", function(e) {
                    if(e) {
                        rapid.post({
                            url: url,
                            data: "id=" + id + "&state=" + (buttonText == "禁用" ? "0" : "1"),
                            responseMsg: false,
                            complete: function() {
                                callback();
                            }
                        });
                    }
                });
        };

    var _addOrUpdateFields = function(action, e) {
        var __grid = this;

        rapid.post({
            url: action === "add" ? __URL_FORM_FIELD_ADD : __URL_FORM_FIELD_UPDATE,
            data: e.serializeJson(),
            success: function() {
                if(action === "add") {
                    var __form_id = e.ui("form_id").val();
                    e.reset().ui("form_id").val(__form_id);
                } else {
                    e.hide();
                }
                __grid.reload();
            }
        });
    };

    var _showAddOrUpdateForm = function(data) {

            rapid(E.window(E.dataview())).window({
                title: data === null ? "创建表单" : "修改 " + data.name + " 表单",
                disposable: true,
                tag: {
                    data: data
                },
                buttons: [{
                    "保存": function() {
                        var __wnd = this,
                            __url = rapid.isEmpty(this.tag("data")) ? __URL_FORM_ADD : __URL_FORM_UPDATE;

                        if(this.tag("dv").valid()) {
                            rapid.post({
                                url: __url,
                                data: this.tag("dv").serializeJson(),
                                success: function() {
                                    __wnd.hide();
                                    rapid("#lstForm").list().reload();
                                }
                            });
                        }
                    }
                }],
                oninit: function() {
                    var __dv = rapid($(this.element).children("form")).dataview({
                        paramFields: ["id"],
                        fields: [{
                            title: "名称", name: "name", editor: {
                                validator: {
                                    rules: {required: true, maxlength: 100}
                                }
                            }
                        }, {
                            title: "编号", name: "code", editor: {
                                validator: {
                                    rules: {required: true, maxlength: 100}
                                }
                            }
                        }, {
                            title: "每行列数", name: "colsize", extraLabel: "建议采用“自动配置”", editor: {
                                type: "picker",
                                selectIndex: 0,
                                dataSource: [{
                                    text: "自动配置", value: 0
                                }, {
                                    text: "1列", value: 1
                                }, {
                                    text: "2列", value: 2
                                }, {
                                    text: "3列", value: 3
                                }, {
                                    text: "4列", value: 4
                                }, {
                                    text: "6列", value: 6
                                }, {
                                    text: "12列", value: 12
                                }],
                                validator: {
                                    rules: {required: true}
                                }
                            }
                        }, {
                            title: "类型", name: "type", editor: {
                                type: "radiolist",
                                defaultValue: 1,
                                dataSource: RES.ARR_FORM_TYPE
                            }
                        },{
                            title: "绑定模型", name: "model_cn",size: 12,
                            editor: {
                                name: "model",
                                type: "picker",
                                tip: "请选择...",
                                autoReload: true,
                                textField: "model_cn",
                                valueField: "model",
                                dataSource: {
                                    textField: "cnname",
                                    valueField: "name",
                                    url: __URL_ROOT + "/getModel"
                                },
                                validator: {
                                    rules: {required: false}
                                }
                            }
                        },{
                            title: "上级动态表单", name: "parentname",size: 12,
                            editor: {
                                name: "parentid",
                                type: "picker",
                                tip: "请选择...",
                                autoReload: true,
                                textField: "parentname",
                                valueField: "parentid",
                                dataSource: {
                                    textField: "name",
                                    valueField: "id",
                                    url: __URL_ROOT + "/getParentForms"
                                },
                                validator: {
                                    rules: {required: false}
                                }
                            }
                        },{
                            title: "上链方式", name: "blockchainmode",size: 12,
                            editor: {
                                name: "blockchainmode",
                                type: "picker",
                                tip: "请选择...",
                                autoReload: true,
                                textField: "codename",
                                dataSource: {
                                    textField: "codename",
                                    valueField: "customid",
                                    url: __URL_ROOT + "/getBlockChainMode"
                                },
                                validator: {
                                    rules: {required: false}
                                }
                            }
                        },/* {
                            title: "是否第三方数据源", name: "is_source", align: "center", width: 80,
                            formatter: function(value, text, css) {
                                var __text = "";
                                if(value == 1) {
                                    css.color = 1;
                                    __text = "是";
                                } else {
                                    __text = "否";
                                }
                                return __text;
                            },
                            editor: {
                                name: "is_source", type: "checkbox", mode: "switch", checked: false,
                                text: ["是", "否"],
                                value: [1, 0],
                                onchange: function(e) {
                                    if(rapid.isEmpty(this.value()) || this.value() == 0) {
                                        e.ui("source_name").disabled(true);
                                    }else{
                                        e.ui("source_name").disabled(false);
                                    }
                                }
                            }
                        }, {
                            title: "数据源名称(目前只支持视图)",id:"source_name", name: "source_name", width: 80,
                            editor: {
                                disabled: true,
                                validator: {
                                    rules: {required: false}
                                }
                            }
                        },*/{
                            title: "排序号",name: "sort", width: 100, editor: {
                                validator: {
                                    rules: {
                                        integer: true,
                                        min: 1,
                                        max: 9999
                                    }
                                }
                            }
                        },{
                            title: "备注", name: "note", size: 12, editor: true
                        }]
                    });

                    this.tag("dv", __dv);

                    var __data = this.tag("data");
                    if(rapid.hasValue(__data)) {
                        __dv.bind(__data);

                        if(__data.is_source == "1" && !rapid.isEmpty(__data.source_name)){

                            rapid.ui("#source_name").disabled(false);
                        }
                    }
                }
            }).show();
        },
        _initUi_ = function() {
            /* var _app = rapid("#grdLifecycExample").grid();*/
            //查询
            rapid.ui("#txtSearch").on("submit", function() {
                rapid("#lstForm").list().load({
                    data: {
                        name: this.val()
                    }
                });
            });
        },
        _initFormList = function() {
            rapid("#lstForm").list({
                dataSource: {
                    valueField: "id",
                    type: "post",
                    url: __URL_FORM_FIND
                },
                textFormatter: function(data) {

                    var _name = data.name;

                    if(!rapid.isEmpty(data.code)) {
                        _name = data.name + "|" + data.code;
                    }

                    if(data.type == 0) {
                        return E.text({cssClass: "r-cl-4-7"}, _name) + " " + E.text({cssClass: "fal fa-copy r-cl-4-7"});
                    }

                    if(data.state == "0") {
                        return KIT.getDisabledText(_name);
                    }
                    return _name;
                }
            }).on("select", function(e) {
                rapid("#grd").grid().tag("form_id", e.value()).settings({
                    addable: true,
                    singleActions: [{
                        text: "禁用",
                        icon: "fa-ban",
                        handler: function(btn) {
                            var __s = this,
                                __selection = this.current();

                            _toggleDisabled(__URL_FORM_FIELD_TOGGLE_DISABLED, __selection.ui("id").val(), __selection.ui("title").val(),
                                "字段", btn.text(), function() {
                                    __s.reload();
                                });
                        },
                        filter: function(item, btn) {
                            if(item.state == 0) {
                                btn.text("启用").icon("fa-check");
                            }
                        }
                    },{
                        text: "自动编号",
                        icon: "fa-edit",
                        toolbar: false,
                        handler: function () {
                            var _this = this;
                            var _id = _this.keySelection() + "";

                            var __codeData = _this.current().__p_data;

                            if (rapid.isEmpty(_id) || _id == "-") {
                                return;
                            }

                            rapid("#wndAutoCode").window({
                                title: "编号规则设置",
                                size: "xl",
                                height: "100%",
                                buttons: [{
                                    "保存": function(e) {
                                        var s = this;
                                        var __dataview = rapid("#frmAutoCode").dataview();

                                        if(!__dataview.valid()) {
                                            return;
                                        }

                                        rapid.confirm("确定要保存吗？", function(e) {

                                            var data = __dataview.serializeJson();

                                            data.id = _id;

                                            if(e) {
                                                rapid.post({
                                                    url: __URL_ROOT + "/saveAutocodeRule",
                                                    data: data,
                                                    success: function(result) {
                                                        s.hide();
                                                        _this.reload();
                                                    }
                                                });
                                            }
                                        });
                                    }
                                }],
                                onInit: function () {
                                },
                                onShow: function () {
                                    var __dv = rapid("#frmAutoCode").dataview();

                                    if(__codeData.is_autocode == '1'){

                                        __dv.bind(__codeData);

                                        rapid.ui("#prefix1").disabled(false);
                                        rapid.ui("#prefix2").disabled(false);
                                        rapid.ui("#serial_number").disabled(false);
                                        rapid.ui("#separator").disabled(false);
                                    }


                                    var __data = __dv.serializeJson();

                                    if(__data.is_autocode == "1"){

                                        _bindAutoCode(__data);
                                    }
                                },
                                onHide: function() {
                                    rapid("#frmAutoCode").dataview().reset();
                                }
                            }).show();
                        }
                    }]
                }).load({
                    data: "form_id=" + e.value()
                });

                rapid("#grdrole").grid().tag("row_id", e.value()).settings({
                    addable: true
                }).load({
                    data: "row_id=" + e.value()
                });

            }).load();
        },

        _initFormListItemMenu = function() {
            $("#lstForm").on("contextmenu", ".r-item", function(e) {

                rapid.popupmenu({
                    actionPalette: {
                        bgColor: 1
                    },
                    offset: e,
                    actions: [{
                        text: "编辑",
                        icon: "fa-edit",
                        handler: function() {
                            _showAddOrUpdateForm(rapid("#lstForm").list().selection()[0].data());
                        }
                    }, {
                        id: "toggleState",
                        text: "禁用",
                        icon: "fa-ban",
                        handler: function(btn) {
                            var __selection_data = rapid("#lstForm").list().selection()[0].data();

                            _toggleDisabled(__URL_FORM_TOGGLE_DISABLED, __selection_data.id, __selection_data.name,
                                "表单", btn.text(), function() {
                                    rapid("#lstForm").list().reload();
                                    rapid("#grd").grid().clear();
                                });
                        }
                    }, {
                        id: "createMenu",
                        text: "创建菜单",
                        handler: function(e) {
                            _createExampleMenu(rapid("#lstForm").list().selection()[0].data());
                        }
                    }],
                    onshow: function() {
                        var __selection_data = rapid("#lstForm").list().selection()[0].data();

                        if(__selection_data.type == 1) {
                            if(__selection_data.state == 0) {
                                this.action("toggleState").text("启用").icon("fa-check");
                            }
                            this.action("createMenu").text("创建菜单");
                        } else {
                            this.action("toggleState").visible(false);
                            this.action("createMenu").visible(false);
                        }
                    }
                });
            });
        },
        _initExampleMenu_ = function() {
            rapid("#frmExampleMenu").dataview({
                colSize: 1,
                fields: [{
                    title: "菜单", name: "menu_type", width: 220,
                    editor: {
                        name: "pid",
                        type: "picker",
                        tip: "请选择...",
                        editable: false,
                        dataSource: {
                            textField: "name",
                            valueField: "id",
                            url: __URL_ROOT + "/getMenusDatasource"
                        },
                        validator: {
                            rules: {required: true}
                        }
                    }
                }]
            });

            rapid("#frmAutoCode").dataview({
                colSize: 1,
                fields: [{
                    title: "是否开启自动编号", name: "is_autocode", align: "center", width: 80,
                    formatter: function(value, text, css) {
                        var __text = "";
                        if(value == 1) {
                            css.color = 1;
                            __text = "是";
                        } else {
                            __text = "否";
                        }
                        return __text;
                    },
                    editor: {
                        name: "is_autocode",id:"is_autocode", type: "checkbox", mode: "switch", checked: false,
                        text: ["是", "否"],
                        value: [1, 0],
                        onchange: function(e) {
                            if(rapid.isEmpty(this.value()) || this.value() == 0) {
                                e.ui("prefix1").disabled(true);
                                e.ui("prefix2").disabled(true);
                                e.ui("serial_number").disabled(true);
                                e.ui("separator").disabled(true);

                                $("#idview").html("")
                            }else{
                                e.ui("prefix1").disabled(false);
                                e.ui("prefix2").disabled(false);
                                e.ui("serial_number").disabled(false);
                                e.ui("separator").disabled(false);

                                var __data = rapid("#frmAutoCode").dataview().serializeJson();

                                if(__data.is_autocode == "1"){

                                    _bindAutoCode(__data);
                                }
                            }
                        }
                    }
                },{
                    title: "前缀1 (代码或年月日)", name: "prefix1",id:"prefix1", width: 220,
                    editor: {
                        tip: "代码或年月日...",
                        disabled: true,
                        editable: false,
                        defaultValue: "XX",
                        validator: {
                            rules: {required: false}
                        },
                        onchange: function (e) {

                            var __data = rapid("#frmAutoCode").dataview().serializeJson();
                            _bindAutoCode(__data)
                        }
                    }
                },{
                    title: "前缀2 (代码或年月日)", name: "prefix2",id:"prefix2", width: 220,
                    editor: {
                        tip: "代码或年月日...",
                        disabled: true,
                        editable: false,
                        defaultValue: "年月日",
                        validator: {
                            rules: {required: false}
                        },
                        onchange: function (e) {

                            var __data = rapid("#frmAutoCode").dataview().serializeJson();
                            _bindAutoCode(__data)
                        }
                    }
                },{
                    title: "流水号(长度)", name: "serial_number",id:"serial_number", width: 220,
                    editor: {
                        editable: false,
                        disabled: true,
                        defaultValue:3,
                        validator: {
                            rules: {required: true,integer:true}
                        },
                        onchange: function (e) {

                            var __data = rapid("#frmAutoCode").dataview().serializeJson();
                            _bindAutoCode(__data)
                        }
                    }
                },{
                    title: "分隔符", name: "separator",id:"separator", width: 220,
                    editor: {
                        type: "picker",
                        disabled: true,
                        tip: "请选择...",
                        editable: false,
                        defaultValue: "-",
                        defaultText:"- (分隔符)",
                        dataSource:__SEPARATOR_TYPES,
                        validator: {
                            rules: {required: false}
                        },
                        onchange: function (e) {

                            var __data = rapid("#frmAutoCode").dataview().serializeJson();
                            _bindAutoCode(__data)
                        }
                    }
                }]
            });
        },
        _createExampleMenu = function(__slt) {
            var __grid = this;
            rapid("#wndExampleMenu").window({
                title: "创建菜单",
                size: "xs",
                buttons: [{
                    "保存": function(e) {
                        var s = this;
                        var __dataview = rapid("#frmExampleMenu").dataview();

                        if(!__dataview.valid()) {
                            return;
                        }
                        rapid.confirm("确定要保存吗？", function(e) {
                            var data = __dataview.serializeJson();
                            data.exampleName = __slt.name;
                            data.exampleCode = __slt.code;
                            if(e) {
                                rapid.post({
                                    id: "saveExampleMenu",
                                    url: __URL_ROOT + "/saveExampleMenu",
                                    data: data,
                                    success: function(result) {
                                        s.hide();
                                        __grid.reload();
                                    }
                                });
                            }
                        });
                    }
                }],
                onHide: function() {
                    rapid("#frmExampleMenu").dataview().reset();
                }
            }).show();
        },

        _initGrid = function() {
            rapid("#grd").grid({
                height: "100%",
                rowHeight: "auto",
                bodyPalette: {
                    bd: false
                },
                detailed: true,
                updatable: true,
                pageable: false,
                dataSource: {
                    type: "post",
                    url: __URL_FORM_FIELDS_FIND
                },
                keyFields: ["id"],
                paramFields: ["id", "form_id", {
                    name: "state", serializable: false
                }],
                fields: __GRID_FIELDS

            }).on("beforeadd", function(e) {
                e.ui("form_id").val(this.tag("form_id"));

            }).on("beforeupdate", function(e) {
                var __value = this.current().ui("type").val();
                _setDataSourceUi(__value, e);
                // _setUploaderFileSizeUi(__value, e);

            }).on("add", function(e) {
                _addOrUpdateFields.call(this, "add", e);

            }).on("update", function(e) {
                _addOrUpdateFields.call(this, "update", e);
            });
        };

    var _addOrUpdateRoles = function(action, e) {
        var __grid = this;

        rapid.post({
            url: action === "add" ? __URL_FORM_ROLES_ADD : __URL_FORM_ROLES_UPDATE,
            data: $.extend({}, e.serializeJson(), {
                row_id: rapid("#grdrole").grid().tag("row_id"),
                conflict_id: e.ui("conflict_id").val()
            }),
            success: function(result) {

                e.hide();
                rapid.success("保存成功。", function() {
                    __grid.reload();
                }, false);
            }
        });
    };

    var _initGridRole = function() {
        rapid("#grdrole").grid({
            height: "100%",
            rowHeight: "auto",
            bodyPalette: {
                bd: false
            },
            detailed: true,
            updatable: true,
            removable: true,
            pageable: false,
            dataSource: {
                type: "post",
                url: __URL_FORM_ROLES_FIND
            },
            keyFields: ["conflict_id"],
            paramFields: ["conflict_id", "row_id"],
            fields: [{
                title: "角色类型", name: "attrib_01_cn", size: 6, frozen: true, width: 140,
                editor: {
                    name: "attrib_01",
                    type: "picker",
                    tip: "请选择...",
                    textField: "attrib_01_cn",
                    valueField: "attrib_01",
                    autoReload: true,
                    dataSource: {
                        textField: "codename",
                        valueField: "customid",
                        url: "/sysadmin/api/getCodeListByParentCustomId",
                        data: "leaf=2&codeType=FORM_DATA_ROLE_TYPE"
                    },
                    validator: {
                        rules: {required: true}
                    }
                }
            }, {
                title: "角色", name: "attrib_02_cn", size: 6, frozen: true, width: 140,
                editor: {
                    name: "attrib_02",
                    type: "picker",
                    tip: "请选择...",
                    textField: "attrib_02_cn",
                    valueField: "attrib_02",
                    autoReload: true,
                    dataSource: {
                        textField: "name",
                        valueField: "id",
                        url: "/sysadmin/role/getAllRoleInfo"
                    },
                    validator: {
                        rules: {required: true}
                    }
                }
            }, {
                title: "是否终审", name: "attrib_03", align: "center", width: 80,
                formatter: function(value, text, css) {
                    var __text = "";
                    if(value == 1) {
                        css.color = 1;
                        __text = "是";
                    } else {
                        __text = "否";
                    }
                    return __text;
                },
                editor: {
                    name: "attrib_03", type: "checkbox", mode: "switch", checked: false,
                    text: ["是", "否"],
                    value: [1, 0]
                }
            }, {
                title: "审核顺序", name: "attrib_11", size: 6, width: 140,
                editor: {
                    type: "picker",
                    dataSource: __AUDIT_SEQS
                }
            },{
                title: "是否全数据权限", name: "attrib_15", size: 6, align: "center", width: 140,
                formatter: function (value, text, css) {
                    var __text = "";
                    if (value == 1) {
                        css.color = 1;
                        __text = "是";
                    } else {
                        __text = "否";
                    }
                    return __text;
                },
                editor: {
                    name: "attrib_15", type: "checkbox", mode: "switch", checked: false,
                    text: ["是", "否"],
                    value: [1, 0]
                }
            }]
        }).on("add", function(e) {
            _addOrUpdateRoles.call(this, "add", e);

        }).on("update", function(e) {
            _addOrUpdateRoles.call(this, "update", e);
        }).on("remove", function(ids) {
            var __grid = this;
            rapid.post({
                url: __URL_FORM_ROLES_REMOVE,
                data: {
                    ids: ids
                },
                success: function() {
                    __grid.reload();
                }
            });
        });
    };

    var _getPrefixInteger = function (value, len) {
        // 当值大于长度限制值时，返回原值
        if (value > Number(Array(3).join(9) + 9))
            return value
        else
            return (Array(len).join(0) + value).slice(-len);
    };

    var _getPrefixStr = function (data){

        var __date = new Date();

        var __year = __date.getFullYear();
        var __month = __date.getMonth() + 1 < 10 ? "0" + (__date.getMonth() + 1) : __date.getMonth() + 1;
        var __day = __date.getDate() < 10 ? "0" + __date.getDate() : __date.getDate();
        var __dateStr = "";
        if("年月日" == data){
            __dateStr = __year + __month + __day;
        }else if("年月" == data){
            __dateStr = __year + __month;
        }else if("年" == data){
            __dateStr = __year;
        }else{
            __dateStr = data;
        }

        return __dateStr;
    };

    var _bindAutoCode = function (data){

        var __serialNumber = _getPrefixInteger(1, parseInt(data.serial_number));
        var __viewCode = _getPrefixStr(data.prefix1) + data.separator + _getPrefixStr(data.prefix2) +  data.separator + __serialNumber;

        $("#idview").html(__viewCode)
    };

    rapid.FormDesigner(function() {
        _initFormList();
        _initUi_();
        _initFormListItemMenu();

        _initGrid();

        _initGridRole();

        _initExampleMenu_();

        rapid.ui("#btnAddForm").on("click", function() {
            _showAddOrUpdateForm(null);
        });

    }).init();

})
(rapid.html.Element, rapid.kit, rapid.res);